package start.doubudouyin.controller;

import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import start.doubudouyin.entity.DateNum;
import start.doubudouyin.entity.UserActiveNum;
import start.doubudouyin.entity.Usersinfo;
import start.doubudouyin.entity.UserGenderNum;
import start.doubudouyin.service.IdgenerateService;
import start.doubudouyin.service.UsersinfoService;
import start.doubudouyin.utils.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/usersinfo")
@CrossOrigin(origins = "http://localhost:5173/")
public class UsersController {
    @Resource
    private UsersinfoService usersinfoService;
    @Resource
    private IdgenerateService idgenerateService;

    //登录
    @GetMapping("/userlogin")
    public Result UserLogin(@RequestParam("phone") String phone, @RequestParam("password") String password) {
        phone = usersinfoService.isPhoneExist(phone);
        Date date = new Date();
        if (phone == null) {
            return Result.error("300", "该手机号未注册，请先注册!");
        } else {
            String userId = usersinfoService.UserLogin(phone, MD5.Encrypt(password));
            if (userId == null) {
                return Result.error("300", "账号或密码错误，请重新输入!");
            }
            if (usersinfoService.isUserOnline(userId) == 1) {
                return Result.error("300", "用户在线，请勿重复登陆!");
            }
            if (usersinfoService.updatelastloginTime(date, userId) <= 0) {
                return Result.error("300", "系统错误，请稍后再试!");
            }
            if (usersinfoService.updateonlineStatus(1, userId) <= 0) {
                return Result.error("300", "系统错误，请稍后再试!");
            }
            return Result.success("登录成功!", userId);
        }
    }

    //注册
    @PutMapping("/userregister")
    @Transactional(rollbackFor = Exception.class)
    public Result UserRegister(@RequestBody Usersinfo usersinfo) {
        //命名一些变量去存储信息，便于理解
        String phone = usersinfo.getPhone();
        String password = usersinfo.getPassword();
        String idcard = usersinfo.getIdcard();
        //获取时间对象
        Date date = new Date();
        //提前赋值给账号创建时间变量
        usersinfo.setCreateTime(date);
        //检查手机号是否注册
        if (usersinfoService.isPhoneExist(phone) != null) {
            return Result.error("300", "手机号已经被注册，请重新输入!");
        }
        //把加密后的密码存入用户信息实体
        usersinfo.setPassword(MD5.Encrypt(password));
        //检查身份证是否重复
        if (usersinfoService.isIdcardExist(MD5.Encrypt(idcard)) != null) {
            return Result.error("300", "身份证已经被注册，请检查输入!");
        }
        //把加密后的身份证存入用户信息实体
        usersinfo.setIdcard(MD5.Encrypt(idcard));
        //若是当天首个注册或者上传视频的用户
        if (idgenerateService.isDateExist(Time.getDate(date)) == null) {
            //生成用户id
            String userId = Idgenerate.userIdgenerate(1);
            usersinfo.setUserId(userId);
            //如果用户信息成功注册并插入用户信息表
            if (usersinfoService.UserRegister(usersinfo) > 0) {
                //再去往表里插入当天日期记录
                idgenerateService.insertDate(date);
                //根据日期更新最后注册的序号
                idgenerateService.updateRegisternum(Time.getDate(date));
                usersinfoService.insertUsersPrefer(usersinfo.getUserId());
                return Result.success("注册成功!", null);
            }
        }
        //非当天首个注册或上传视频的用户
        else {
            //根据当天最后注册的序号+1去生成id
            String userId = Idgenerate.userIdgenerate
                    (idgenerateService.getRegisternum(Time.getDate(date)) + 1);
            usersinfo.setUserId(userId);
            if (usersinfoService.UserRegister(usersinfo) > 0) {            //如果用户信息成功注册并插入用户信息表
                idgenerateService.updateRegisternum(Time.getDate(date));    //根据日期更新最后注册的序号
                usersinfoService.insertUsersPrefer(usersinfo.getUserId());
                return Result.success("注册成功!", null);
            }
        }
        return Result.error("300", "注册失败!");
    }

    //根据id获取用户信息
    @GetMapping("/getuserinfo")
    public Result getUserinfo(@RequestParam("userId") String userId) {
        Usersinfo usersinfo = usersinfoService.getUserById(userId);
        usersinfo.setPassword(null);
        usersinfo.setIdcard(null);
        return Result.success(usersinfo);
    }

    //忘记密码
    @PutMapping("/updatepassword")
    public Result UpdatePassword(@RequestParam("phone") String phone, @RequestParam("idcard") String idcard,
                                 @RequestParam("password") String password) {
        if (usersinfoService.VerifyUser(phone, MD5.Encrypt(idcard)) == null) {
            return Result.error("300", "用户不存在，请检查手机号和身份证号");
        }
        if (usersinfoService.UpdatePassword(phone, MD5.Encrypt(idcard), MD5.Encrypt(password)) <= 0) {
            return Result.error("300", "系统错误，请稍后再试!");
        }
        return Result.success();
    }

    //根据id和身份证号修改密码
    @PutMapping("/updatePasswordByIdCard")
    public Result updatePasswordByIdCard(@RequestParam("userId") String userId, @RequestParam("idcard") String idcard,
                                     @RequestParam("newPassword") String newPassword){
        if (usersinfoService.VerifyId(userId, MD5.Encrypt(idcard)) == null) {
            return Result.error("300", "身份证号错误");
        }
        if (usersinfoService.UpdatePasswordById(userId, MD5.Encrypt(newPassword)) <= 0) {
            return Result.error("300", "系统错误，请稍后再试!");
        }
        return Result.success();
    }

//    根据id、旧密码修改密码
    @PutMapping("/updatePasswordByOld")
    public Result updatePasswordByOld(@RequestParam("userId") String userId,@RequestParam("password") String password,
                                      @RequestParam("newPassword") String newPassword){
        if (usersinfoService.VerifyPassword(userId, MD5.Encrypt(password)) == null) {
            return Result.error("300", "密码错误");
        }
        if(usersinfoService.UpdatePasswordById(userId, MD5.Encrypt(newPassword))<=0){
            return Result.error("300","系统错误，请稍后再试!");
        }else{
            return Result.success();
        }
    }

    @GetMapping("/findAll")
    public Result findAll(){
        List<Usersinfo> list=usersinfoService.findAll();
        if(list==null){
            return Result.error("300","获取用户信息失败");
        }else{
            return Result.success(list);
        }
    }

    //根据id删除用户
    @DeleteMapping("/deletebyId")
    public Result deleteById(@RequestParam("userId") String userId){
        if(usersinfoService.removeById(userId)){
            return Result.success("删除成功");
        }else{
            return Result.error("300","删除失败");
        }
    }

    //退出登录
    @PutMapping("/userLogout")
    public Result UserLogout(@RequestParam("userId") String userId) {
        if (usersinfoService.updateonlineStatus(0, userId) <= 0) {
            return Result.error("300", "系统错误，请稍后再试!");
        }
        return Result.success("退出成功!");
    }

    //修改手机号
    @PutMapping("/updatePhone")
    public Result updatePhone(@RequestParam("userId") String userId, @RequestParam("oldPhone") String oldPhone,
                              @RequestParam("newPhone") String newPhone) {
        if (usersinfoService.VerifyPhone(userId, oldPhone) == null) {
            return Result.error("300", "原手机号错误");
        }
        if(usersinfoService.isPhoneExist(newPhone)!=null){
            return Result.error("300","手机号已经被注册，请重新输入!");
        }
        if(usersinfoService.UpdatePhone(userId,newPhone )<=0){
            return Result.error("300","系统错误，请稍后再试!");
        }else{
            return Result.success();
        }
    }

    //获取30天内每天的用户注册数量
    @GetMapping("/getUserRange30")
    public Result getUserRange30(){
        DateNum userRange30 = usersinfoService.getUserRange30();
        return Result.success(userRange30);
    }

    //获得性别人数
    @GetMapping("/getUserGenderNum")
    public Result getGenderNum(){
        UserGenderNum  userGenderNum= usersinfoService.getUserGenderNum();
        return Result.success(userGenderNum);
    }

    //获取活跃的用户和非活跃用户的数量（七天内登录过的是活跃的，否则为非活跃的）
    @GetMapping("/getUserActiveNum")
    public Result getUserActiveNum(){
        UserActiveNum userActiveNum=usersinfoService.getUserActiveNum();
        return Result.success(userActiveNum);
    }
}
